<?php
/**
 * Created by PhpStorm.
 * User: simon
 * Date: 2016/3/9
 * Time: 11:28
 */

namespace App\Models;


use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;

class BaseModel extends Model
{
    public function formatMe()
    {

    }

    public function setBlankAttributes($properties)
    {
        foreach ($properties as $key => $value) {
            $this->setBlankAttribute($key, $value);
        }
    }

    public function setBlankAttribute($key, $value)
    {
        $oldValue = $this->getAttribute($key);
        if (empty($oldValue) && !empty($value)) {
            $this->_setAttribute($key, $value);
        }
    }

    public function forceFill(array $attributes)
    {
        $this->_setAttributes($attributes);
    }

    public function _setAttributes($properties)
    {
        foreach ($properties as $key => $value) {
            $this->_setAttribute($key, $value);
        }
    }

    public function _setAttribute($key, $value)
    {
        $getMethod = "get_" . $key;
        $setMethod = "set_" . $key;
        if (!method_exists(get_class($this), $getMethod) && !method_exists(get_class($this), $setMethod)) {
            return;
        }
        parent::setAttribute($key, $value);
    }

    public function _getAttribute($key, $defaultValue = "")
    {
        $getMethod = "get_" . $key;
        if (!method_exists(get_class($this), $getMethod)) {
            return $defaultValue;
        }
        parent::getAttribute($key);
    }

    public function current_timestamp()
    {
        return Carbon::now();
    }


    /**
     * @return String
     */
    public function getTable()
    {
        return $this->table;
    }

    /**
     * @param String $table
     */
    public function setTable($table)
    {
        $this->table = $table;
    }

    /**
     * @return String
     */
    public function getPrimaryKey()
    {
        return $this->primaryKey;
    }

    /**
     * @param String $primaryKey
     */
    public function setPrimaryKey($primaryKey)
    {
        $this->primaryKey = $primaryKey;
    }

    public function getPrimaryKeyValue()
    {
        return $this->_getAttribute($this->primaryKey);
    }

    public function scopeOfCompany($query, $companyId)
    {
        return $query->where("company_id", $companyId);
    }
}